package com.example.test.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.example.test.entity.Type;
import com.example.test.entity.common.Message;
import com.example.test.entity.common.SimpleMessage;
import com.example.test.enums.ErrorCodeEnum;
import com.example.test.enums.MessageEnum;
import com.example.test.service.impl.TypeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 王雪杰
 * @date 2021/5/18 10:58
 */
@Service
@Slf4j
public class ExcelService {

    @Resource
    private TypeServiceImpl typeService;

    /**
     * 下载单据详情数据
     *
     * @param response 响应
     * @throws IOException
     */
    public void downloadAskCarSheetDetail(HttpServletResponse response) throws IOException {

        // 处理下载数据
        List<Type> typeList = typeService.listTypes();
        // 处理下载
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("分类详情信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Type.class).sheet("分类详情信息123").doWrite(new ArrayList<Type>());
    }

    /**
     * 上传单据信息
     *
     * @param file 文件
     * @return SimpleMessage
     */
    @Transactional(rollbackFor = Exception.class)
    public Message uploadSheetInfo(MultipartFile file) throws IOException {
        // 接收解析出的目标对象（Type）
        List<Type> types = new ArrayList<>();
        // excel中表的列要与对象的字段相对应
        InputStream inputStream = file.getInputStream();
        EasyExcel.read(inputStream, Type.class, new AnalysisEventListener<Type>() {
            // 每解析一条数据都会调用该方法
            @Override
            public void invoke(Type type, AnalysisContext analysisContext) {
                log.info("文件信息[{}]", JSON.toJSONString(type));
                types.add(type);
            }

            // 解析完毕的回调方法
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                log.info("读取完毕:共[{}]行", types.size());
                // 执行后续操作
            }
        }).sheet().doRead();
        // 输出 file
        System.out.println(file.getName());
        // 输出 分类详情信息.xlsx
        System.out.println(file.getOriginalFilename());
        return new Message(MessageEnum.GENERAL_REQUEST_SUCCESS, types);
    }
}
